<template>

  <div class="VfullTextSearch_box">
    <pre-zjcl class="prezjcl" :inline="false" ref="PreZjcl"></pre-zjcl>

    <div class="search_box">
      <select class="searchType" ref="searchType">
        <option value="1">证据目录</option>
        <option value="2">证据内容</option>
      </select>
      <input ref="content" placeholder="请输入关键字进行检索..." type="text" @keydown.13="search"/>
      <i class="el-icon-search word16" title="搜索" @click="search"></i>
    </div>
    <div class="table_list" style="height: calc(100% - 45px);">
      <el-table :data="searchResult_table" class="word14" style="width: 100%;height: calc(100% - 35px);"
                tooltip-effect="dark" ref="table" :cell-style="cellStyle" empty-text="暂无数据">
        <el-table-column type="index" label="序号" :index="indexMethod" width="55">
        </el-table-column>
        <el-table-column prop="MLXSMC" label="目录名称" width="280" show-overflow-tooltip>
          <template slot-scope="{ row, column, $index }">
            <div class="word14 nowrap" :title="row.MLXSMC" v-html="getItem(row,1)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="WJXSMC" label="文件名称" width="200" show-overflow-tooltip>
          <template slot-scope="{ row, column, $index }">
            <div class="word14 nowrap" :title="row.WJXSMC" v-html="row.WJXSMC"></div>
          </template>
        </el-table-column>
        <el-table-column prop="WJLX" label="文件类型" width="80" show-overflow-tooltip header-align="center"
                         align="center">
        </el-table-column>
        <el-table-column prop="TEXT" label="文件内容" show-overflow-tooltip header-align="center" align="center">
          <template slot-scope="{ row, column, $index }">
            <div class="word14 nowrap" :title="row.Text" v-html="getItemText(row)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="" width="120" label="操作" header-align="center" align="center">
          <template slot-scope="{ row, column, $index }">
            <img class="row_btn" title='预览' @click='view(row)' src='~@/assets/img/ck.png'>
            <img class="row_btn" title='加入证据' @click='add(row)' src='~@/assets/img/jrzj.png'>
            <img class="row_btn" title='投影' @click='toScreen(row)' src='~@/assets/img/ty.png'
                 v-show="isPlay">
          </template>
        </el-table-column>
      </el-table>
      <div style="position: relative;height: 35px;">
        <el-pagination background :total="searchResult.length" :page-size="pageSize" layout="prev, pager, next"
                       :current-page.sync="currentPage"
                       style="position: absolute;top: 50%;transform: translate(0,-50%);">
        </el-pagination>
      </div>
    </div>

    <vmodal :modalshow="modalshow" modaltitle="加入证据" :closeonclickmodal="false"
            :styleobj="{width: '300px',height: '437px'}" @hide="modalshow=false">
      <div slot="modal" style="width:100%;height:100%;background-color: white">
        <div style="width:100%;height:calc(100% - 50px);overflow: auto;">
          <el-tree ref="catalogMLTree" highlight-current render-after-expand node-key='id' default-expand-all
                   :data="catalogML" :props="catalogProps" v-if="catalogML.length" style="width:100%">
          </el-tree>
        </div>
        <div style="text-align: right;height: 50px">
          <el-button style="margin:5px 10px 0 0" size="small" type="plain" @click="cancelAddMindMapping">取消
          </el-button>
          <el-button style="margin:5px 10px 0 0" size="small" type="primary" @click="addMindMapping">确认
          </el-button>
        </div>
      </div>
    </vmodal>

  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import {action} from '../common/quantity'
  import A from '../common/typeActions'
  import commonServer from '../server/common/commonServer.js'
  // import bus from '../../common/bus.js'
  import SQLiteHelper from '../common/SQLiteHelper'
  import evidenceCatalogTree from '../config/evidenceCatalogTree'

  const path = require('path')

  export default {
    name: 'vfull-text-search',
    data () {
      return {
        imgSource: [],
        searchvalue: '',
        modalshow: false,
        catalogProps: {
          children: 'children',
          label: 'alias'
        },
        searchResult: [],
        catalogML: [],
        currentPage: 1,
        pageSize: 100
      }
    },
    computed: {
      ...mapState({
        retrieveDataSource: state => state.appearCourt.retrieveDataSource,
        evidenceCatalogTreeData: state => state.preplan.evidenceCatalogTreeData,
        casePath: state => state.appearCourt.casePath,
        isPlay: state => state.slideEditor.isPlay
      }),
      searchResult_table () {
        let startNum = (this.currentPage - 1) * this.pageSize
        let endNum = this.currentPage * this.pageSize - 1
        return this.searchResult.filter(
          (item, index) => index >= startNum && index <= endNum
        )
      }
      // ...mapGetters({
      //   catalogML: "catalogML"
      // })
    },
    methods: {
      cellStyle () {
        return {
          padding: '3px 0px',
          verticalAlign: 'top !important'
        }
      },
      indexMethod (index) {
        return (this.currentPage - 1) * this.pageSize + 1 + index
      },
      add (item) {
        this.catalogML = evidenceCatalogTree.getCatalogML()
        this.modalshow = true
        this.item = item
      },
      cancelAddMindMapping () {
        this.modalshow = false
        this.$refs.catalogMLTree && this.$refs.catalogMLTree.setCurrentNode({})
      },
      addMindMapping () {
        let tree = this.$refs.catalogMLTree
        if (!tree) return
        let node = tree.getCurrentNode()
        tree.setCurrentNode({})
        if (!node) return this.$alert('没有选中节点', '提示', {type: 'warning'})

        let transferData = []
        if (this.item.NodeID) {
          transferData = [
            {
              ID: this.item.MLBH,
              NodeID: this.item.MLBH,
              NodeParentID: '',
              MLXSMC: this.item.MLXSMC,
              FileType: 'dir',
              WJHZ: ''
            }, {
              ID: this.item.WJBH,
              NodeID: this.item.NodeID,
              NodeParentID: this.item.MLBH,
              MLXSMC: this.item.WJXSMC,
              FileType: 'file',
              WJHZ: this.item.WJHZ
            }]
          // let _node = this.$parent.$refs.prePlan.$refs.docDossierTree.getNode(this.item.NodeID)
          //
          // if (this.item.WJLX === '文书卷宗' && _node) {
          //   transferData.push(_node.data)
          //   while ((_node = _node.parent)) {
          //     let pnode = _node.data
          //     let isExist = transferData.some(_item => _item.NodeID === pnode.NodeID)
          //     if (!isExist) transferData.push(pnode)
          //     if (pnode.FileType === 'dir') break
          //   }
          // }
        } else {
          transferData.push({
            FileType: 'file',
            ID: this.item.WJBH,
            MLXSMC: this.item.WJXSMC,
            NodeID: this.item.WJBH,
            NodeParentID: '',
            WJHZ: this.item.WJHZ || this.item.WJKZM
          })
        }

        let data = {node: node, dossiers: JSON.stringify(transferData)}

        this.$eventBus.$emit('ADD_FILES_INTO_CATALOG', data)

        this.modalshow = false
      },
      getItem (item, mark) {
        let str = this.searchvalue
        let v = str.split(' ')
        v = v.map(item => {
          return item.split('').join('\\s*')
        })
        let search = v.join('|')
        let re = new RegExp('(' + search + ')')
        return mark === 1
          ? item.MLXSMC.replace(re, '<span style="color: red">$1</span>')
          : item.WJXSMC.replace(re, '<span style="color: red">$1</span>')
      },

      getItemText (item) {
        if (!item.Text || item.Text.trim() === '') return

        let str = this.searchvalue
        let v = str.split(' ')
        v = v.map(item => {
          return item.split('').join('\\s*')
        })
        let temp = v.join('|')
        let re = '\\n[^\\n]*(' + temp + ')+[^\\n]*\\n'
        let marcharr = item.Text.match(re)
        if (marcharr) {
          marcharr = marcharr[0]
        } else {
          return item.Text
        }
        return marcharr.replace(
          new RegExp('(' + temp + ')', 'gim'),
          '<span style="color: red">$1</span>'
        )
      },

      // 搜索
      async search (ev) {
        try {
          this.searchvalue = this.$refs.content.value
          let searchType = this.$refs.searchType.value
          if (!this.searchvalue) {
            ev.type === 'click' && this.$message('请输入搜索关键字')
            return
          }

          // this.loadStatus({loading: true, loadingText: "搜索中，请稍候..."});
          // if (!this.retrieveDataSource || !this.retrieveDataSource.length) {
          this.searchResult = await this.$store.dispatch(action.appearCourt.initRetrieveDataSource, {
            value: this.searchvalue,
            type: searchType
          })
          // }

          // let v = this.searchvalue.split(" ");
          // v = v.map(item => item.split("").join("\\s*")).join("|");
          // let re = new RegExp("(" + this.searchvalue.trim() + ")", "gim");
          // this.searchResult = this.retrieveDataSource.filter(x => {
          //   return re.test(x.MLXSMC) || re.test(x.TEXT) || re.test(x.WJXSMC)
          // })
          // for (let vv of this.retrieveDataSource) {
          //   if () {
          //     this.searchResult.push(vv);
          //   }
          // }
        } catch (e) {
          console.error(e)
          this.$alert('检索内容失败', '错误', {type: 'error'})
        } finally {
          // this.loadStatus({loading: false});
        }
      },

      async view (item) {
        console.log(item)
        // 预览图片
        let pdf = null
        if (process.browser) {
          pdf = await this.$api.post.getEvidenceMaterialByCode({
            fileID: item.WJBH,
            fileType: item.WJLX === '电子卷宗' ? 0 : 1,
            dbPath: this.$store.state.appearCourt.casePath
          })
        } else {
          pdf = await commonServer.getPDFFileByID(item.WJBH)
        }

        if (!pdf) return this.$message({type: 'error', message: '预览失败'})
        if (/mp3|mp4/i.test(item.WJHZ || item.WJKZM)) {
          const {dir, name} = path.parse(this.casePath)
          this.$refs.PreZjcl.show(path.resolve(dir, name, pdf))
        } else if (/docx?|pdf|jpe?g|png|bmp|gif|ofd/i.test(item.WJHZ || item.WJKZM)) {
          this.$refs.PreZjcl.show(pdf)
        }
      },
      async toScreen (item) {
        try {
          this.loadStatus({
            loading: true,
            loadingText: '正在投影证据材料，请稍等...'
          })
          // 添加至投影区
          let images = []
          let srcImg = await SQLiteHelper.GetEvidenceMaterial([item.WJBH])
          if (srcImg) {
            srcImg.forEach(item => {
              images.push(item.IMG)
            })
            this.$store.dispatch(A.SLIDEEDITOR.SetTemporaryFile, images)
          } else {
            this.$alert('添加至投影区失败', '错误', {type: 'error'})
          }
        } catch (error) {
          this.$alert(error.message, '错误', {type: 'error'})
        } finally {
          this.loadStatus({loading: false})
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .VfullTextSearch_box {
    width: 100%;
    height: 100%;
    position: relative;
    padding: 5px;
    overflow-x: auto;
  }

  .VfullTextSearch_box .search_box {
    height: 35px;
    width: 100%;
    margin-bottom: 10px;
    position: relative;

    .searchType {
      width: 120px;
      height: 100%;
    }
  }

  .search_box input {
    padding-left: 10px;
    width: calc(100% - 120px);
    height: 100%;
    font-size: 16px;
    font-family: 微软雅黑;
    position: relative;
    border-style: solid;
    border-width: 1px;
  }

  .search_box i {
    position: absolute;
    height: 100%;
    width: 35px;
    text-align: center;
    line-height: 35px;
    right: 0;
    cursor: pointer;
  }

  .search_box i:hover {
    background-color: #8dbbfd;
    color: #fff;
  }

  .row_btn {
    vertical-align: top !important;
  }
</style>
